package com.autoagent.ai_live_master.scriptGeneration.utils;

import com.autoagent.ai_live_master.scriptGeneration.dto.ProductDesc;
import com.autoagent.ai_live_master.scriptGeneration.entity.CompleteScripts;
import com.autoagent.ai_live_master.scriptGeneration.entity.MethodologySummary;
import com.autoagent.ai_live_master.scriptGeneration.entity.ScriptFeatures;
import com.autoagent.ai_live_master.scriptGeneration.mapper.CompleteScriptsMapper;
import com.autoagent.ai_live_master.scriptGeneration.mapper.MethodologySummaryMapper;
import com.autoagent.ai_live_master.scriptGeneration.mapper.ScriptFeaturesMapper;
import com.autoagent.ai_live_master.scriptGeneration.service.ProductMaterialsService;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Slf4j
@Component
public class FusionDataBuilder {

    private final MethodologySummaryMapper methodologySummaryMapper;
    private final ScriptFeaturesMapper scriptFeaturesMapper;
    private final CompleteScriptsMapper completeScriptsMapper;
    private final ProductMaterialsService productMaterialsService;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    public FusionDataBuilder(MethodologySummaryMapper methodologySummaryMapper,
                             ScriptFeaturesMapper scriptFeaturesMapper,
                             CompleteScriptsMapper completeScriptsMapper,
                             ProductMaterialsService productMaterialsService) {
        this.methodologySummaryMapper = methodologySummaryMapper;
        this.scriptFeaturesMapper = scriptFeaturesMapper;
        this.completeScriptsMapper = completeScriptsMapper;
        this.productMaterialsService = productMaterialsService;
    }

    public Map<String, String> buildFusionState(Long userId, ProductDesc productDesc, List<Long> referenceScriptIds) {
        log.info("[FusionBuilder] 开始构建 fusion_data，用户ID: {}", userId);

        // 获取方法论
        MethodologySummary methodology = methodologySummaryMapper.getLatestByUserId(userId);
        String methodologyContent = methodology != null ? methodology.getTechniqueSummary() : "";
        log.info("[FusionBuilder] 方法论内容长度: {}", methodologyContent.length());

        // 获取 ScriptFeatures
        ScriptFeatures features = scriptFeaturesMapper.getLatestByUserId(userId);
        String featuresContent = features != null ? features.getScriptFeatures() : "";
        log.info("[FusionBuilder] ScriptFeatures 内容长度: {}", featuresContent.length());

        // 获取参考脚本
        List<String> referenceScriptContents = new ArrayList<>();
        if (referenceScriptIds != null && !referenceScriptIds.isEmpty()) {
            log.info("[ScriptOutline] 获取参考脚本内容，IDs: {}", referenceScriptIds);
            List<CompleteScripts> referenceScripts = completeScriptsMapper.selectBatchIds(referenceScriptIds);
            log.info("[ScriptOutline] 获取到参考脚本数量: {}", referenceScripts.size());
            for (CompleteScripts script : referenceScripts) {
                if (script != null && script.getContent() != null) {
                    referenceScriptContents.add(script.getContent());
                }
            }
        } else {
            log.info("[ScriptOutline] 没有提供参考脚本IDs");
        }

        // 获取产品资料
        String productMaterialsContent = "";
        try {
            // 首先通过productDesc搜索产品素材（产品名）
            if (productDesc != null && productDesc.getTag() != null && !productDesc.getTag().isEmpty()) {
                log.info("[FusionBuilder] 开始通过产品描述搜索产品素材: [标签: {}, 内容: {}]", 
                         productDesc.getTag(), productDesc.getContent());
                String searchResult = productMaterialsService.searchProductMaterials(productDesc.getTag());
                if (searchResult != null && !searchResult.isEmpty()) {
                    productMaterialsContent = searchResult;
                    log.info("[FusionBuilder] 搜索产品素材成功，内容长度: {}", productMaterialsContent.length());
                } else {
                    log.warn("[FusionBuilder] 搜索产品素材未找到结果");
                }
            } else {
                log.info("[FusionBuilder] 产品描述为空或内容为空");
            }
        } catch (Exception e) {
            log.error("[FusionBuilder] 获取产品资料失败: {}", e.getMessage(), e);
        }

        // 构建 fusion_data Map
        Map<String, Object> fusionData = new HashMap<>();
        fusionData.put("methodology", methodologyContent);
        fusionData.put("scriptFeatures", featuresContent);
        
        // 如果productDesc不为空，将标签和内容都放入fusion_data
        if (productDesc != null) {
            Map<String, String> productDescMap = new HashMap<>();
            productDescMap.put("tag", productDesc.getTag());
            productDescMap.put("content", productDesc.getContent());
            fusionData.put("productDesc", productDescMap);
        } else {
            fusionData.put("productDesc", null);
        }
        
        fusionData.put("referenceScripts", referenceScriptContents);
        fusionData.put("productMaterials", productMaterialsContent);

        // 转 JSON
        String fusionDataJson;
        try {
            fusionDataJson = objectMapper.writeValueAsString(fusionData);
            log.info("[FusionBuilder] fusion_data JSON 构建成功，长度: {}", fusionDataJson.length());
        } catch (Exception e) {
            log.error("[FusionBuilder] fusion_data 转 JSON 失败: {}", e.getMessage(), e);
            fusionDataJson = "{}";
        }

        Map<String, String> state = new HashMap<>();
        state.put("fusion_data", fusionDataJson);
        return state;
    }

}

